<template>
	<qh-page-view title="待支付">
		<view class="wait-pay">
			<view class="pay-top">
				<view class="pay-top-time">
					<text>支付剩余时间</text>
					<text>{{time_desc}}</text>
				</view>
				<view class="pay-top-money">
					<text>￥</text>
					<text>{{order.all_money*1}}</text>
				</view>
			</view>
			<!-- #ifdef MP-WEIXIN -->
			<view class="pay-choose-list-box" v-if="payList[0]==1">
				<view class="pay-choose-list">
					<view class="pay-choose-type">
						<image src="/static/images/pay-icon-weChat.png"></image>
						<view>微信支付</view>
					</view>
					<view class="radio-box">
						<qh-radio v-model="pay_type" :active-value="1" padding="20" @change="selPayType"></qh-radio>
					</view>
				</view>
			</view>
			<!-- #endif -->

			<!-- #ifdef MP-ALIPAY -->
			<view class="pay-choose-list-box" v-if="payList[3]==1">
				<view class="pay-choose-list">
					<view class="pay-choose-type">
						<image src="https://safood-1317438654.cos.ap-guangzhou.myqcloud.com/tempImage/1729071401670f89294d672.png" style="width:52rpx;height:52rpx"></image>
						<view>支付宝支付</view>
					</view>
					<view class="radio-box">
						<qh-radio v-model="pay_type" :active-value="4" padding="20" @change="selPayType"></qh-radio>
					</view>
				</view>
			</view>
			<!-- #endif -->

			<view class="pay-choose-list-box" v-if="payList[1]==1">
				<view class="pay-choose-list">
					<view class="pay-choose-type">
						<image src="/static/images/pay-icon-balance.png"></image>
						<view>
							<text>余额支付</text>
							<block v-if="vip.vid">
								<text class="pay-vip-balance">（<text :style="vip.balance*1>=order.all_money*1?'color:#333':''">￥{{vip.balance}}</text>）</text>
								<text v-if="vip.balance*1<order.all_money*1" class="pay-act-button" @tap.stop="toRecharge">充值</text>
							</block>
							<text v-else class="pay-act-button" @tap.stop="toRegister">注册</text>
						</view>
					</view>
					<view class="radio-box">
						<qh-radio v-model="pay_type" :active-value="2" :disabled="!(vip.vid && vip.balance>=order.all_money)" padding="20" @change="selPayType"></qh-radio>
					</view>
				</view>
			</view>
			<view class="pay-choose-list-box" v-if="payList[2]==1&&vip.vid &&vip.balance*1>0.01&&order.all_money*1> 0.01">
				<view class="pay-choose-list">
					<view class="pay-choose-type">
						<image src="/static/images/pay-icon-combination.png"></image>
						<view>组合支付</view>
					</view>
					<view class="radio-box">
						<qh-radio v-model="pay_type" :active-value="3" padding="20" @change="selPayType"></qh-radio>
					</view>
				</view>
				<view class="pay-combination-box" v-if="pay_type==3">
					<view class="pay-combination-list">
						<!-- #ifdef MP-ALIPAY -->
						<text>支付宝</text>
						<!-- #endif -->
						<!-- #ifdef MP-WEIXIN -->
						<text>微信</text>
						<!-- #endif -->
						<view class="pay-combination-money-box">
							<text>￥</text>
							<input @input="inputThirdMoney" type="digit" :value="third_pay_money"></input>
						</view>
					</view>
					<view class="pay-combination-list">
						<text>余额</text>
						<view class="pay-combination-money-box">
							<text>￥</text>
							<input @input="inputBalance" type="digit" :value="balance_pay_money"></input>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部 -->
		<view class="pay-button-box" :style="footerStyle">
			<view class="submit-report-zindex">
				<view class="pay-button" @tap.stop="submitPay" v-if="canClick">确认支付</view>
				<view class="pay-button pay-button-disabled" v-else>确认支付</view>
			</view>
		</view>
		<!-- 会员支付密码弹框 -->
		<template-password v-if="showPayPassword" v-model="password" :pay="true" :price="order.all_money" @success="vipCardPay" @cancel="cancelPassword">
		</template-password>
	</qh-page-view>
</template>

<script>
	var app = getApp().globalData;

	import templatePassword from '@/components/template-password.vue';
	export default {
		components: {
			templatePassword,
		},
		data() {
			return {
				template_list: [], //订阅消息
				pay_type: 0, //支付方式 1微信 2余额 3组合
				goodsList: [],
				showPayPassword: false,
				canClick: true,
				third_pay_money: '', //微信支付金额
				balance_pay_money: '', //余额支付的金额
				payMoney: 0, //最终支付金额
				expiration_time: '', //订单过期时间
				pick_code: '', //提货码
				order: {
					all_money: 0
				}, //订单详情
				vip: {}, //会员信息
				time_desc: '00:00:00', //支付倒计时
				payData: {}, //微信支付参数
				password: "",
				old_pay_type: "",
				order_no: "",
				payList: [],
				isPay: false, //支付宝支付状态是否进行支付
			};
		},
		computed: {
			footerStyle() {
				return `padding-bottom:${this.$store.bottomHeight + 20}rpx;height: ${this.$store.bottomHeight + 136}rpx;`;
			},
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		async onLoad(options) {
			if (!options || !options.order_no) {
				uni.navigateBack({
					delta: 1
				});
			}
			this.setData({
				order_no: options.order_no,
				time_desc: options.time ? options.time : '',
				order: {
					all_money: ''
				}
			});
			this.getOrderInfo();
		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		async onShow() {
			await this.$onLaunched;
			!this.isPay && this.getVipInfo();

			// #ifdef MP-ALIPAY
			if (this.isPay) {
				uni.showLoading({
					title: '订单信息查询中',
				});
				this.searchOrder(this.order_no, 0);
			}
			// #endif
		},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload() {
			clearInterval(this.timer);
		},
		methods: {
			//获取订单支付信息
			async getOrderInfo() {
				const {
					status,
					data,
					message
				} = await this.$request('SmallProgramApi/Pay/getWaitPayDetail_v2', {
					order_no: this.order_no
				});
				if (status != 1) return uni.showModal({
					title: '错误提示',
					content: message ? message : '请求发生错误，请稍后再试！',
					showCancel: false,
					confirmText: '返回',
					success: (res) => {
						if (res.confirm) {
							uni.navigateBack({
								delta: 1
							});
						}
					}
				});
				data.order.all_money = data.order.all_money * 1;
				this.order = data.order;
				this.payList = data.payList;
				this.canClick = true;
				this.template_list = data.template_list;

				this.setBlessing();

				if (data.payList[0] == 1) {
					this.pay_type = 1; //微信
				} else if (data.payList[1] == 1) {
					if (data.vip && data.vip.vid && parseFloat(data.vip.balance) >= parseFloat(data.order.all_money)) {
						this.pay_type = 2; //会员余额
					}
				} else if (data.payList[3] == 1) {
					this.pay_type = 4; //支付宝
				} else {
					this.canClick = false;
					uni.showModal({
						title: '错误提示',
						content: '商家未开启支付方式，请稍后再试！',
						showCancel: false,
						confirmText: '返回',
						success: (res) => {
							if (res.confirm) {
								uni.navigateBack({
									delta: 1
								});
							}
						}
					});
				}
				this.time(data.expiration_time);
			},
			//设置祝福语
			async setBlessing() {
				let blessData = uni.getStorageSync('blessData')
				if (blessData) {
					const {
						data,
						status,
						message
					} = await this.$request('Blessing/Applets/addBlessing', Object.assign({
						orderId: this.order.id
					}, JSON.parse(blessData)))

					if (status != 1) {
						uni.showToast({
							url: message,
							icon: 'none'
						})
					}
				}
			},
			//获取会员信息
			async getVipInfo() {
				const {
					status,
					vip_data
				} = await this.$request('SmallProgramApi/Pay/getUserDetail');
				if (status == 1) {
					vip_data.balance = vip_data.balance * 1;
					this.vip = vip_data;
				} else {
					this.vip = {};
				}
			},

			//定时器
			//选择支付方式
			selPayType(type) {
				this.canClick = true;
				if (type == 2) {
					//余额
					if (this.vip.vid) {
						if (parseFloat(this.vip.balance) < parseFloat(this.order.all_money)) {
							this.canClick = false;
						}
					}
				} else if (type == 3) {
					if (!parseFloat(this.third_pay_money) || parseFloat(this.third_pay_money) < 0.01) {
						this.canClick = false;
					}

					if (!parseFloat(this.balance_pay_money) || parseFloat(this.balance_pay_money) < 0.01) {
						this.canClick = false;
					}
				}
			},
			//去充值
			toRecharge() {
				uni.navigateTo({
					url: '/pages/mine/recharge/recharge'
				});
			},
			//去激活会员
			toRegister() {
				uni.navigateTo({
					url: '/pages/mine/card/card'
				});
			},
			//输入微信支付金额
			inputThirdMoney(e) {
				var payMoney = parseFloat(this.order.all_money);
				var oldValue = e.detail.value;
				console.log(oldValue.indexOf('.'));

				if (oldValue != '' && oldValue.indexOf('.') != -1 && oldValue.indexOf('.') < getApp().globalData.roundPrice(oldValue.length - 3)) {
					oldValue = oldValue.substr(0, oldValue.indexOf('.') + 3);
				}

				var money = parseFloat(oldValue);

				if (money > payMoney) {
					money = oldValue = getApp().globalData.roundPrice(payMoney - 0.01);
				} else {
					if (oldValue != parseFloat((money * 1).toFixed(2))) {
						money = oldValue = getApp().globalData.roundPrice(parseInt(money * 100) / 100);
					}
				}

				var balance_pay_money = getApp().globalData.roundPrice(payMoney - money);
				var balance = parseFloat(this.vip.balance);

				if (balance_pay_money > balance) {
					balance_pay_money = balance;
				}

				this.setData({
					third_pay_money: oldValue,
					balance_pay_money: balance_pay_money,
					canClick: true
				});
			},
			//输入余额支付金额
			inputBalance: function(e) {
				var payMoney = parseFloat(this.order.all_money);
				var oldValue = e.detail.value;
				console.log(oldValue.indexOf('.'));

				if (oldValue != '' && oldValue.indexOf('.') != -1 && oldValue.indexOf('.') < getApp().globalData.roundPrice(oldValue.length - 3)) {
					oldValue = oldValue.substr(0, oldValue.indexOf('.') + 3);
				}

				var money = parseFloat(oldValue);

				if (money > payMoney) {
					money = oldValue = getApp().globalData.roundPrice(payMoney - 0.01);
				} else {
					if (oldValue != parseFloat((money * 1).toFixed(2))) {
						money = oldValue = getApp().globalData.roundPrice(parseInt(money * 100) / 100);
					}
				}

				var third_pay_money = getApp().globalData.roundPrice(payMoney - money);
				var balance = parseFloat(this.vip.balance);

				if (third_pay_money > balance) {
					third_pay_money = balance;
				}

				this.setData({
					third_pay_money: third_pay_money,
					balance_pay_money: oldValue,
					canClick: true
				});
			},

			//取消会员密码
			cancelPassword: function() {
				console.log('cancelPassword')
				this.setData({
					showPayPassword: false,
					password: '',
					canClick: true
				});
			},
			//点击支付按钮
			submitPay: function() {
				this.setData({
					old_pay_type: this.pay_type
				});
				if (JSON.stringify(this.payData) != '{}' && this.pay_type == 1) {
					//微信支付
					this.wxPay();
					return;
				} else if (JSON.stringify(this.payData) != '{}' && this.pay_type == 4) {
					this.aliPay();
					//支付宝支付
					return;
				}

				this.setData({
					old_pay_type: this.pay_type
				});
				// #ifdef MP-WEIXIN
				var template_list = this.template_list;
				if (template_list && template_list.length > 0) {
					//后台配置了模板推送
					uni.requestSubscribeMessage({
						tmplIds: this.template_list,
						success: (res) => {
							this.verifyPay(); //验证支付
						},
						fail: (res) => {
							console.error(res)
						}
					});
				} else {
					this.verifyPay(); //验证支付
				}
				// #endif
				// #ifdef MP-ALIPAY
				this.verifyPay(); //验证支付
				// #endif
			},
			//验证支付
			verifyPay: function() {
				if (!this.canClick) {
					return;
				}

				var pay_type = this.pay_type;

				if (pay_type == 1) { // 微信支付
				} else if (pay_type == 2) { //余额支付
				} else if (pay_type == 4) { //支付宝支付
				} else if (pay_type == 3) {
					//组合支付
					var third_pay_money = this.third_pay_money;
					var balance_pay_money = this.balance_pay_money;

					if (!parseFloat(third_pay_money) || parseFloat(third_pay_money) < 0.01) {
						uni.showToast({
							// #ifdef MP-ALIPAY
							title: '请输入支付宝支付金额',
							// #endif
							// #ifdef MP-WEIXIN
							title: '请输入微信支付金额',
							duration: 1000,
							// #endif
							icon: 'none',
						});
						return;
					}

					if (!parseFloat(balance_pay_money) || parseFloat(balance_pay_money) < 0.01) {
						uni.showToast({
							title: '请输入余额支付金额',
							icon: 'none',
							// #ifdef MP-ALIPAY
							duration: 1000,
							// #endif
						});
						return;
					}
				} else {
					uni.showToast({
						title: '请选择支付方式',
						icon: 'none',
						duration: 800
					});
					return;
				}
				// #ifdef MP-ALIPAY
				console.log('开始调用授权')
				my.getAuthCode({
					// 订单服务授权：order_service。如需同时获取用户多项授权，可在 scopes 中传入多个 scope 值。
					scopes: ['order_service'],
					success: (res) => {
						// 订单服务授权成功
						this.toSubmit(); //去提交支付信息
					},
					fail: (res) => {
						console.log(res)
						// 订单服务授权失败，根据自己的业务场景来进行错误处理
					},
				});
				// #endif
				// #ifdef MP-WEIXIN
				this.toSubmit(); //去提交支付信息
				// #endif
			},
			//确认支付
			toSubmit: function() {
				this.setData({
					canClick: false
				});
				var that = this;
				uni.showLoading({
					title: '请求中...',
					mask: true
				});
				var third_pay_money = this.third_pay_money; //

				var balance_pay_money = this.balance_pay_money;
				var pay_type = this.pay_type;
				getApp().globalData.sendRequest({
					url: '/Pay/getOrderPaymentData_v2',
					type: "post",
					showLoading: false,
					data: {
						order_no: that.order_no,
						pay_type: pay_type,
						third_pay_money: third_pay_money,
						balance_pay_money: balance_pay_money
					},
					success: function(res) {
						uni.hideLoading();

						if (res.status == 1) {
							if (pay_type == 1 || pay_type == 3) {
								that.setData({
									payData: res.data
								});
								that.wxPay();
							} else if (pay_type == 2) {
								that.setData({
									showPayPassword: true,
									password: '',
								});

							} else if (pay_type == 4) {
								that.payData = res.data;
								that.aliPay();
							}
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none',
								duration: 1500
							});
							that.setData({
								canClick: true
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						that.setData({
							canClick: true
						});
					}
				});
			},
			// 会员卡支付
			vipCardPay: function() {
				var password = this.password;
				var order_no = this.order_no;
				var that = this;
				getApp().globalData.sendRequest({
					url: '/Pay/vipCardPay_v2',
					type: "post",
					loadTitle: '支付中...',
					data: {
						password: password,
						order_no: order_no
					},
					success: function(res) {
						if (res.status == 1) {
							that.setData({
								showPayPassword: false,
								pick_code: res.pick_code ? res.pick_code : ''
							});
							that.paySuccess();
							uni.removeStorageSync('blessData')
						} else if (res.status == 2) {
							that.setData({
								canClick: true
							});
							uni.showModal({
								title: '提示',
								content: '您的会员卡余额不足',
								showCancel: true,
								confirmText: '去充值',
								confirmColor: '#ff3d3d',
								success: function(res) {
									if (res.confirm) {
										uni.navigateTo({
											url: '../../mine/recharge/recharge'
										});
									}
								}
							});
						} else {
							that.setData({
								canClick: true,
								password: '',
							})

							uni.showToast({
								title: res.msg,
								icon: "none",
								duration: 1500,
								showCancel: false,
							});
						}
					}
				});
			},
			wxPay: function() {
				var that = this;
				var payData = this.payData;
				var order_no = that.order_no; // 调取微信支付。。。

				uni.requestPayment({
					timeStamp: payData.timeStamp,
					nonceStr: payData.nonceStr,
					package: payData.package,
					signType: payData.signType,
					paySign: payData.paySign,
					success: function(re) {
						console.log(re);

						if (re.errMsg == 'requestPayment:ok') {
							// 查询订单支付状态
							uni.showLoading({
								title: '订单信息查询中',
								// #ifndef MP-ALIPAY
								mask: true,
								// #endif
							});
							that.searchOrder(order_no, 0); //查询订单
						} else {
							console.log(re);
							that.setData({
								canClick: true
							});
						}
					},
					complete: function() {
						if (that.pay_type == 3) {
							//组合支付则清除支付参数（）因为金额可以随意组合
							that.setData({
								payData: {}
							});
						}

						that.setData({
							canClick: true
						});
					}
				});
			},
			aliPay() {
				this.isPay = true
				my.tradePay({
					// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
					tradeNO: this.payData.trade_no,
					success: (res) => {
						console.log('success:', res)
						this.searchOrder(this.order_no, 0); //查询订单
					},
					fail: (res) => {
						console.log('fail:', res)
						this.searchOrder(this.order_no, 0); //查询订单
					}
				});
			},
			//查询订单支付状态
			searchOrder: function(order_no, count) {
				var that = this;
				getApp().globalData.sendRequest({
					url: '/Pay/searchPayOrder_v1',
					type: "post",
					showLoading: false,
					data: {
						order_no: order_no
					},
					success: function(res) {
						if (res.status == 1) {
							uni.hideLoading();
							this.isPay = false
							if (res.pick_code) {
								that.setData({
									pick_code: res.pick_code
								});
							}

							that.paySuccess();
						} else if (res.status == 2) {
							count++;

							if (count > 10) {
								uni.hideLoading();
								uni.showModal({
									title: '提示',
									content: res.msg,
									showCancel: false,
									confirmText: '确定',
									confirmColor: '#ff3d3d'
								});
							} else {
								setTimeout(function() {
									that.searchOrder(order_no, count);
								}, 1000);
							}
						} else {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								confirmText: '确定',
								confirmColor: '#ff3d3d'
							});
						}
					}
				});
			},
			//支付成功处理
			paySuccess: function() {
				getApp().globalData.userLogin();
				uni.redirectTo({
					url: "../paySuccess/paySuccess?money=" + this.order.all_money + "&order_no=" + this
						.order_no + "&pick_code=" + this.pick_code + "&order_genre=" + this.order.order_genre +
						"&order_id=" + this.order.id
				});
			},
			//订单剩余支付时间倒计时
			time: function(expiration_time) {
				var end2 = 0;

				if (expiration_time) {
					end2 = expiration_time.replace(/-/g, '/'); //   console.log(end2)
				} else {
					end2 = 0;
				}

				var end_time = new Date(end2); //设置截止时间

				var end = end_time.getTime();
				this.timer = setInterval(function() {
					var ls = new Date().getTime();
					var str = this.countTime(end, ls); // console.log(str);

					this.setData({
						time_desc: str
					});

					if (str == '' || str == '00:00:00') {
						clearInterval(this.timer);
						uni.showModal({
							title: '提示',
							content: '订单已超时，请重新下单',
							showCancel: false,
							confirmText: '退出',
							confirmColor: '#ff3d3d',
							success: function(res) {
								uni.navigateBack({
									delta: 1
								});
							}
						});
					}

					ls += 1000;
				}.bind(this), 1000);
			},

			countTime(end, ls) {
				var leftTime = end - ls; //时间差

				var h, m, s, ms;

				if (leftTime >= 0) {
					h = Math.floor(leftTime / 1000 / 60 / 60 % 24); //时

					m = Math.floor(leftTime / 1000 / 60 % 60); //分

					s = Math.floor(leftTime / 1000 % 60); //秒

					ms = Math.floor(leftTime % 1000); //毫秒

					ms = ms < 100 ? "0" + ms : ms;
					s = s < 10 ? "0" + s : s;
					m = m < 10 ? "0" + m : m;
					h = h < 10 ? "0" + h : h;
					var str = h + ":" + m + ":" + s;
					return str;
				} else {
					return '';
				}
			}

		}
	};
</script>
<style>
	@import "./waitPay.css";
</style>
